package Huihu.src.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Talkreceive implements Runnable{
    DatagramSocket socket=null;
    private int fromPort;
    private String msgFrom;

    public Talkreceive(int fromPort,String msgFrom) {
        this.fromPort = fromPort;
        this.msgFrom=msgFrom;
        try{
            socket=new DatagramSocket(fromPort);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //接收数据
        while (true) {
            try{
                byte[] bus = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bus, 0, bus.length);
                socket.receive(packet);
                String str=new String(packet.getData(), 0, packet.getLength());
                System.out.println(msgFrom+":"+str);
                if (str.equals("byte")) {
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
